package leetcode107

type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

func levelOrderBottom(root *TreeNode) [][]int {
	res := make([][]int, 0)

	if root == nil {
		return res
	}
	nowLevelNode := []*TreeNode{root}
	tempAllLevelTreeNode := make([][]*TreeNode, 0)
	tempAllLevelTreeNode = append(tempAllLevelTreeNode, nowLevelNode)

	for {
		nextLevelNode := make([]*TreeNode, 0)
		for _, node := range nowLevelNode {
			if node.Left != nil {
				nextLevelNode = append(nextLevelNode, node.Left)
			}

			if node.Right != nil {
				nextLevelNode = append(nextLevelNode, node.Right)
			}

		}
		nowLevelNode = nextLevelNode
		if len(nextLevelNode) == 0 {
			break
		}
		tempAllLevelTreeNode = append(tempAllLevelTreeNode, nowLevelNode)
	}
	for i := len(tempAllLevelTreeNode) - 1; i >= 0; i-- {
		oneLevelVal := make([]int, len(tempAllLevelTreeNode[i]))
		for j := range tempAllLevelTreeNode[i] {
			oneLevelVal[j] = tempAllLevelTreeNode[i][j].Val
		}
		res = append(res, oneLevelVal)
	}
	return res
}
